﻿using System;
using System.Data;
using System.Data.Common;
using Microsoft.Extensions.Options;
using MySqlConnector;
using NetMicro.EventBus.Persistences;

namespace NetMicro.EventBus.MySql
{
    public class TransactionContext : ITransactionContext
    {
        public TransactionContext(IOptionsMonitor<EventBusMySqlOptions> options)
        {
            DbConnection = new MySqlConnection(options.CurrentValue.ConnectionString);
            if (DbConnection.State == ConnectionState.Closed)
                DbConnection.Open();
            Transaction = DbConnection.BeginTransaction();
        }

        public IDbTransaction Transaction { get; private set; }

        private IDbConnection DbConnection { get; }

        public void Commit()
        {
            Transaction?.Commit();
            Transaction = null;
        }

        public void Rollback()
        {
            Transaction?.Rollback();
            Transaction = null;
        }



        #region dispose
        private bool _disposed;
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~TransactionContext() => Dispose(false);

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
                return;
            if (disposing)
            {
                if (Transaction != null)
                    Rollback();
                DbConnection?.Dispose();
            }
            _disposed = true;
        }
        #endregion

    }

}
